import json

from PyQt6.QtWidgets import (QApplication, QMessageBox, QDialog)
import sys
from json_formatter import Ui_jsonFormtter


class MyJsonFormtter(Ui_jsonFormtter, QDialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.show()

        self.pushButton_format.clicked.connect(
            self.do_format_json('format')
        )

        self.pushButton_unformat.clicked.connect(
            self.do_format_json('unformat')
        )
        self.pushButton_copyjson.clicked.connect(
            self.do_copy_json
        )

    def do_copy_json(self):
        board = QApplication.clipboard()
        board.setText(self.plainTextEdit_josn.toPlainText())
        QMessageBox.information(self, '信息提示', '复制成功')

    def do_format_json(self, type):
        def inner_format():
            json_content = self.plainTextEdit_josn.toPlainText()
            if not json_content:
                QMessageBox.warning(self, '信息提示', '请输入内容')
                return
            try:
                if type == 'format':
                    new_content = json.dumps(json.loads(json_content), indent=4, ensure_ascii=False)
                else:
                    new_content = json.dumps(json.loads(json_content), ensure_ascii=False)
                self.plainTextEdit_josn.setText(new_content)
            except Exception as e:
                QMessageBox.warning(self, '信息提示', f'JSON文本格式有误：{e}')
                return
            QMessageBox.information(self, '信息提示', '操作成功')

        return inner_format


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myJsonFormtter = MyJsonFormtter()
    sys.exit(app.exec())
